#include <iostream>
#include <sstream>
#include <stack>
using namespace std;

void test1()
{
	string str1;
	string str2;
	getline(cin, str1);
	getline(cin, str2);

	for (int i = 0; i < str1.size(); ++i)
	{
		for (int j = 0; j < str2.size(); ++j)
		{
			if (str1[i] == str2[j])
			{
				str1.erase(str1.begin() + i);
			}
		}
	}
	cout << str1 << endl;
}

struct ListNode
{
	struct ListNode* next;
	int val;
	ListNode(int val)
		:val(val)
		, next(nullptr)
	{}
};

ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
	stack<ListNode*> st;
	ListNode* ret = nullptr;
	while (pHead1 || pHead2)
	{
		if (pHead1)
		{
			st.push(pHead1);
			pHead1 = pHead1->next;
		}
		if (pHead2)
		{
			st.push(pHead2);
			pHead2 = pHead2->next;
		}
	}
	while (!st.empty())
	{
		ret = st.top();
		st.pop();
		if (ret != st.top())
			break;
		st.pop();
	}
	if (ret)
		ret = ret->next;
	return ret;
}


void test2()
{
	ListNode* node1 = new ListNode(1);
	ListNode* node2 = new ListNode(2);
	ListNode* node3 = new ListNode(3);
	ListNode* node6 = new ListNode(6);
	ListNode* node7 = new ListNode(7);

	ListNode* node4 = new ListNode(4);
	ListNode* node5 = new ListNode(5);

	node1->next = node2;
	node2->next = node3;
	node3->next = node6;
	node6->next = node7;

	node4->next = node5;
	node5->next = node6;

	ListNode* result = FindFirstCommonNode(node1, node4);
	while (result)
	{
		cout << result->val << " ";
		result = result->next;
	}
	cout << endl;
}


void test3()
{
	int n = 0;
	string str;
	cin >> n >> str;

	int a = 0, b = 0, c = 0;
	int i = 0;
	while (i < str.size())
	{
		switch (str[i])
		{
		case 's':
			++a;
			break;
		case 'h':
			++b;
			break;
		case 'y':
			++c;
			break;
		default:
			break;
		}
		++i;;
	}
	cout << a << " " << b << " " << c << endl;
	cout << a * b * c << endl;
}


int main()
{
	test2();

	return 0;
}